package servlet.recipe.page;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import mysql.JdbcUtil;
import servlet.account.control.InfoCheck;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

@WebServlet("/Insert")
@MultipartConfig
public class Insert extends HttpServlet {

    private static final String UPLOAD_DIRECTORY = "chushi/img/recipes"; // 你可以设置上传文件的目录

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 检查用户是否已经登录
        if (new InfoCheck().checkCredentials(req)) {

            req.setAttribute("Login", "Session");
        }

        // 转发到 Insert.jsp 页面
        req.getRequestDispatcher("/chushi/jsp/Insert.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求的编码格式
        req.setCharacterEncoding("UTF-8");

        // 获取请求参数
        String name = req.getParameter("name");
        String description = req.getParameter("description");
        String difficulty = req.getParameter("difficulty");
        String category = req.getParameter("recipe_category");
        String createTime = req.getParameter("createTime");

        // 获取Part对象
        Part part = req.getPart("image");
        // 通过Part对象得到上传的文件名
        String fileName = part.getSubmittedFileName();
        System.out.println("上传文件名：" + fileName);

        // 得到文件存放的路径
        String filePath = req.getServletContext().getRealPath("/")+UPLOAD_DIRECTORY;
        System.out.println("文件存放路径：" + filePath);

        // 上传文件到指定目录
        part.write(filePath + "/" + fileName);

        // 更新数据库插入语句以保存图片路径
        JdbcUtil JDBC = new JdbcUtil();
        String sql = "INSERT INTO recipes(recipe_name, recipe_content, recipe_image, recipe_category, recipe_time, thumbnail) VALUES (?, ?, ?, ?, ?, ?)";
        try (Connection conn = JDBC.connectMySQL();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, name);
            ps.setString(2, description);
            ps.setString(3, UPLOAD_DIRECTORY + "/" + fileName); // 存储图片路径
            ps.setString(4, category);
            ps.setString(5, createTime);
            ps.setString(6, difficulty);
            ps.executeUpdate();
            // 通知用户上传成功
            req.setAttribute("message","success");
            doGet(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            // 处理数据库错误
            resp.getWriter().println("File upload or data insertion failed: " + e.getMessage());
        }
    }
}
